<?php

namespace Vote\Controller;

use Think\Controller;

class IndexController extends CommonController {

    function tt() {
        header("Content-type: text/html; charset=utf-8");       
      /*  $url  = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=UZAokWPrdB3HHy6x80d-t-hTgU31237jPjAvvL0Yh9fqMtI9Qmg2wT7h9MSadjOIFgwKrHRMECctaStseZj8cC0hFvuqGsLbtFChdK6IVB0';
        $data= json_decode(http_get($url),true);
        $list = $data['data']['openid'];
        foreach ($list  as $k=>$v){
            echo 'INSERT INTO v_fsopenid VALUES("'.$v.'");';
        }
        
        
		exit;*/
        // echo '<img src="'.C('IMG_PATH').'uploads/share.jpg">';
echo $_GET['openid'];exit;
		$rs = check_vip($_GET['openid']);
		print_r($rs);exit;
		echo $rs['huiyuan_tel'];exit;
		echo '充值会员卡号:'.$rs['card_no'];
		echo '<br>';
		echo '会员原始积分为:'. getCredits($rs['card_no']);
		echo '<br>';
       // echo '会员充值后积分为:'.addCredits($rs['card_no'],5900);
        // M('Score')->add(array('open_id' => $rs['open_id'], 'card_no' => $rs['card_no'],'score'=>5900, 'ctime' => date('Y-m-d H:i:s', time()))); //积分记录
       // $rs = check_vip('o3Iz7jpuaba-u_iLQlSDyq-Q555k'); //会员信息
        // print_r($rs);
        //print_r(deductCredits('6001660066000000010',1500));
//        $serv = $_REQUEST['serverid'];
//        file_put_contents("./aaaaa.txt", var_export($serv, true));
//        echo $this->ajaxReturn($serv);
    }

    //领取投票者列表
    function index() {
        $this->checkopenid();
        $activityid = $_REQUEST['activity_id']; //当前活动ID
        if (!$activityid) {
            $this->_empty();
        }
        $info = $this->getActivityById($activityid);
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 异步加载信息
     * 
     */
    function ajaxListData() {
        $model = M('User');
        $keywords = $_REQUEST['keywords'];
        if (!empty($keywords)) {
            $map['name'] = array('like', '%' . $keywords . '%');
            $map['id'] = array('eq', $keywords);
            $map['_logic'] = 'OR';
            $where['_complex'] = $map;
        }
        $where['activity_id'] = $_REQUEST['activity_id'];
        $where['state'] = 2;
        $page = intval($_POST['pageNum']); //当前页 
        $total = $model->where($where)->count(); //总记录数 
        $pageSize = 16; //每页显示数 
        $totalPage = ceil($total / $pageSize); //总页数 
        $startPage = $page * $pageSize; //开始记录 
        //构造数组 
        $dataArr['total'] = $total;
        $dataArr['pageSize'] = $pageSize;
        $dataArr['totalPage'] = $totalPage;
        $dataArr['list'] = $model->where($where)->limit($startPage . ',' . $pageSize)->order('vote_num desc,gorder desc,crttime desc')->select();
        //echo $model->getLastSql();exit;
        echo json_encode($dataArr);
    }

    //投票人数
    function joinlist() {
        echo voteJoinList(2);
    }

    //检测openid
    function checkopenid() {
        $openid = wx_openid();
        if (!$openid) {
            $this->_empty();
        }
    }

    //404
    public function _empty() {
        header("HTTP/1.0 404 Not Found"); //使HTTP返回404状态码 
        $this->display("Public:404");
        exit();
    }

    /**
     * 用户报名
     * 
     */
    function join() {
        $rs = check_vip(wx_openid()); //会员信息
        //print_r($rs);exit;
        $userid = intval($_REQUEST['userid']);
        $id = intval($_GET['activity_id']); //活动id
        $gc = M('User');
        $where['open_id'] = wx_openid();
        $where['huiyuan_id'] = $rs['huiyuan_id'];
        $where['state'] = 2;
        $info = $gc->where($where)->find();
        $state = 0;
        if ($rs) {
            if ($userid) {
                $arr['state'] = 3;
                $arr['uptime'] = time();
				$arr['ip'] = $this->get_client_ip();
				$arr['moile_info'] = $_SERVER ['HTTP_USER_AGENT'];
                $state = M('User')->where('id=' . $userid)->save($arr);//更新删除
            }
            if (!$state && $info) {
                $this->redirect('/Index/detail?id=' . $info['id'] . '&activity_id=' . $id);
            }
            $this->assign('huiyuan', 1);
        } else {

            $this->assign('huiyuan', 2);
            //register_page();
        }
        $this->assign('info', $this->getActivityById($id)); //获取活动基本信息
        $this->assign('activityId', $id);
        $this->display();
    }

    /**
     * 保存报名人员信息
     * 
     */
    public function saveAddUser() {
        $rs = check_vip(wx_openid()); //会员信息
        $activityid = $_REQUEST['acid']; //活动ID
        $name = $_REQUEST['name']; //用户名
        $img = $_REQUEST['img']; //用户头像
        $info = $_REQUEST['info']; //用户描述

        $arr['activity_id'] = $activityid;
        $arr['u_type'] = 1;
        $arr['state'] = 2;
        $arr['name'] = $name;
        $arr['uptime'] = $arr['crttime'] = time();
        $arr['img'] = wxdownMediAapi($img);
        $arr['info'] = nl2br($info);
        $arr['huiyuan_id'] = $rs['huiyuan_id'];
        $arr['open_id'] = wx_openid();
		$arr['tel'] = $rs['huiyuan_tel'];
        //添加保存信息

        $where['open_id'] = wx_openid();
        $where['huiyuan_id'] = $rs['huiyuan_id'];
        $s = M('User')->where($where)->find(); //查询是否已经报名过  如果存在不加积分
        M('Wxupload')->add(array('localid' => $_REQUEST['localid'], 'serverid' => $img, 'open_id' => wx_openid(), 'ctime' => time())); //记录微信上传后的数据
       
        $info = M('User')->where(array_merge($where, array('state' => 2)))->find(); //查询报名者信息是否存在  不允许重复入库
        if (!$info) {
            $state = M('User')->add($arr);
        }
        $data['state'] = $state;
        if ($state) {
			$usercount = M('User')->where('state=2')->count();//统计参与人数
			$scwhere['open_id'] = wx_openid();
			$score = M('Score')->where($scwhere)->find();
            //加积分条件
            if ($usercount <= 200 && !$score && !$s) {
                M('Score')->add(array('open_id' => wx_openid(), 'card_no' => $rs['card_no'],'score'=>1500, 'ctime' => date('Y-m-d H:i:s', time()))); //积分记录
                addCredits($rs['card_no'], 1500); //加积分
                $data['showmsg'] = 1; //首次显示注册成功信息
            }
            $data['info'] = "上传成功!";
            $this->ajaxReturn($data);
        } else {
            $data['info'] = "网络异常,请重新上传!";
            $this->ajaxReturn($data);
        }
    }

    //排行榜
    function alex() {
        $this->checkopenid();
        $id = $_REQUEST['activity_id']; //活动ID
        $this->assign('info', $this->getActivityById($id)); //获取活动基本信息
        $this->display();
    }

    //异步加载排行列表
    function rank() {
        $gc = M('User');
        $page = ($_POST['num']); //当前页 
        $pageSize = 10; //每页显示数 
        $last = $page * $pageSize; //开始记录 
        $where['activity_id'] = $_REQUEST['activity_id'];
        $where['state'] = 2;
        $data = $gc->field('id,name,vote_num')->where($where)->order('vote_num desc')->limit(0 . ',' . $last)->select();
        $this->ajaxReturn($data);
    }

    //用户详情
    function userInfo() {
        $userid = intval($_GET['userid']);
        $info = M('User')->where('id=' . $userid)->find();
        $this->assign('data', $info);
        $this->display();
    }

    //获取用户列表
    private function getUserList($activityId) {
        $map['activity_id'] = array('eq', $activityId);
        $gc = M('User');
        $map['u_type'] = array('eq', 1); //个人
        $data = $gc->where($map)->order("gorder asc")->select();
        $this->assign('personal', $data);
        $map['u_type'] = array('eq', 2); //团队
        $this->assign('team', $gc->where($map)->order("gorder asc")->select());
    }

    //详情页
    public function detail() {
        $this->checkopenid();
        $map['id'] = array('eq', $_GET['id']);
        $map['activity_id'] = array('eq', $_GET['activity_id']);
        $gc = M('User');
        $data = $gc->where($map)->find();
        $data or $this->_empty();
        $this->assign('info', $this->getActivityById($_GET['activity_id']));
        $this->assign('data', $data);
        $this->assign('showmsg', $_REQUEST['showmsg']);

        $arr = array(
            "title" => '万元大奖，票选江苏绿地会最萌宝贝！', //转发标题
            "desc" => '5等大奖、39个名额、报名即享1500积分哦~', //转发内容
            "link" => 'http://a.forcent.cn/ldh/vote.php/Index/detail?activity_id=' . $_REQUEST['activity_id'] . '&id=' . $_GET['id'],
            "imgUrl" => C('IMG_PATH') . 'uploads/share.jpg',
            'acid' => $_REQUEST['activity_id']
        );
        $this->assign('sharePackage_detail', json_encode($arr));
        if(3 == $data['state']){
            redirect('join?activity_id='.$_GET['activity_id']);
        }
        if ($data['open_id'] == wx_openid()) {//wx_openid()){
			$rs = check_vip(wx_openid()); //会员信息
			$where['open_id'] = wx_openid();
			$where['state'] = 2;
			M('User')->where($where)->save(array('tel'=>$rs['huiyuan_tel']));
            $this->display('my');
            return;
        }
        $this->display('other');
    }

    //获取活动信息
    private function getActivityById($id) {
        $map['id'] = array('eq', $id);
        $gc = M('Activity');
        $info = $gc->where($map)->order('id desc')->find();
        if ($info['status'] == 1) {
            return $info;
        } else {
            $this->_empty();
        }
    }
	//验证码配置
    function verify() {
		$config =    array(
			'fontSize'    =>    30,    // 验证码字体大小
			'length'      =>    4,     // 验证码位数
			'useNoise'    =>    false, // 关闭验证码杂点
			'codeSet' => '0123456789',
			'fontttf' => '5.ttf',
			'useCurve' => false,
		);
        $Verify = new \Think\Verify($config);
		$Verify->entry();
    
    }

    //投票  本地测试关闭wx_Open
    public function subVote() {
       
        $gc = M('Vote_recode');
        $jsonMsg['status'] = 0;
        $activityId = $_REQUEST['activityid']; //活动ID
        $userid = $_REQUEST['userid']; //用户ID

        if (empty($activityId)) {
            $jsonMsg['info'] = '参数丢失';
            $this->ajaxReturn($jsonMsg);
            exit();
        }
        $time = $this->get_server_time(); //服务器时间
        $activity = $this->getActivityById($activityId);
        if ($activity['start_time'] > $time || $activity['end_time'] < $time) {
            $jsonMsg['info'] = '不在投票时间内，请稍后再来！';
            $this->ajaxReturn($jsonMsg);
            exit();
        }

        $ip = $this->get_client_ip(); //客户端IP
        if ($activity['getian'] == 1) {
            $map['crttime'] = array(array('egt', strtotime(date("Y-m-d 00:00:00"))), array('elt', strtotime(date("Y-m-d 23:59:59"))), 'and');
        }

        $map['openid'] = wx_openid();
        $map['activity_id'] = $activityId; //wx_openid();
        $s = $gc->where($map)->find(); //查询投票记录
        //echo $gc->getLastSql();
        $c = $gc->where($map)->count(); //查询投票次数
  
        if (0 == $activity['repeat']) {
            $rp['user_id'] = $userid;
            $rp['activity_id'] = $activityId;
            $rp['crttime'] = array(array('egt', strtotime(date("Y-m-d 00:00:00"))), array('elt', strtotime(date("Y-m-d 23:59:59"))), 'and');
            $rp['openid'] = wx_openid();
            $rs = $gc->where($rp)->find();
            //echo $gc->getLastSql();
        }
        
        if (0 == $activity['repeat'] && $rs) {
            $jsonMsg['info'] = '不能重复投票！';
            $this->ajaxReturn($jsonMsg);
        }
        if ($s && $c >= $activity['p_stint']) {
           
            if ($activity['getian'] == 1) {
                $jsonMsg['info'] = '您今天已经投过票了，请明天再来！';
                $this->ajaxReturn($jsonMsg);
            } else {
                $jsonMsg['info'] = '你已经投过票了！';
                $this->ajaxReturn($jsonMsg);
            }
        } else {
            
            $verify = $_GET['verify'];
            if (!$verify) {
                $jsons['status'] = 10;
                $this->ajaxReturn($jsons);
            }


            if (false === check_verify($verify)) {
                $jsonMsg['info'] = '验证码错误！';
                $this->ajaxReturn($jsonMsg);
            }

            $arr['user_id'] = $userid;
            $arr['activity_id'] = $activityId;
            $arr['client_ip'] = $ip;
            $arr['openid'] = wx_openid();
            $arr['http_header'] = get_headers();
            $arr['crttime'] = $time;
            $arr['verify'] = $verify;
            $arr['moile_info'] = $_SERVER ['HTTP_USER_AGENT'];
            //print_r($arr);exit;
            $user = M('User');
            $gc->startTrans();
            $user->startTrans();
            $where['id'] = $userid;
            $votenum = $user->where($where)->getField('vote_num'); //查询已有的投票数量
            $updata['vote_num'] = $votenum + 1;
            $gcstate = $gc->add($arr);
            $usersate =  $user->where($where)->save($updata); //更新投票数量
            if ($gcstate && $usersate) {
                $gc->commit();
                $user->commit();
                //voteBrowse($activityId) ;
                $jsonMsg['status'] = 1;
                $jsonMsg['info'] = '投票成功，感谢您的参与！';
                $jsonMsg['data'] = $user->where($where)->getField('vote_num');
                $this->ajaxReturn($jsonMsg);
            } else {
                $gc->rollback();
                $user->rollback();
                $jsonMsg['info'] = '网络异常，请重新投票！';
                $this->ajaxReturn($jsonMsg);
            }
        }
    }

    //分享记录
    function sharelog() {
        $data['open_id'] = wx_openid();
        $data['activity_id'] = $_REQUEST['acid'];
        $data['utime'] = $data['ctime'] = $this->get_server_time();
        $where['open_id'] = wx_openid();
        $where['activity_id'] = $_REQUEST['acid'];
        $gc = M('Sharelog');
        $rs = $gc->where($where)->find();
        if ($rs) {
            $state = $gc->where($where)->save(array('utime' => $this->get_server_time()));
        } else {
            $state = $gc->add($data);
        }
        $this->ajaxReturn($state);
    }

}
